package com.acme.domain;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.acme.domain.request.Request;

public class Writer {
	private static Socket requestSocket;
	private static ExecutorService executor;
	
	Writer(String server,int port) throws IOException{
		requestSocket = new Socket(server,port);
		executor = Executors.newSingleThreadExecutor();
		OutputStream out = requestSocket.getOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(out);
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject("w");
		oos.flush();
	}

	public static void writeRequest(final Request req){
		executor.execute(new Runnable(){
			@Override
			public void run() {
				try {
					OutputStream out = requestSocket.getOutputStream();
					BufferedOutputStream bos = new BufferedOutputStream(out);
					ObjectOutputStream oos = new ObjectOutputStream(bos);
					oos.writeObject(req);
					oos.flush();
				} catch(IOException ex){
					ex.printStackTrace();
				}	
			}
		});
	}
	
	public static void shutdown(){
		executor.shutdown();
	}
	
}
